import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/Login.vue'
import Home from '../views/Home.vue'
import Welcome from '../views/Welcome.vue'
import Users from '../views/user/Users.vue'
import Rights from '../views/power/Rights.vue'
import Roles from '../views/power/Roles.vue'
import EditRole from '../views/power/editRole.vue'
import Cate from '../views/goods/Cate.vue'
import Addcate from '../views/goods/Addcate.vue'
import Editcate from '../views/goods/Editcate.vue'
import Params from '../views/goods/Params.vue'
import GoodsList from '../views/goods/List.vue'
import Add from '../views/goods/Add.vue'
import Order from '../views/order/Order.vue'
import Report from '../views/report/Report.vue'
// 解决ElementUI导航栏中的vue-router在3.0版本以上重复点菜单报错问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}
Vue.use(VueRouter)

const routes = [{
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    children: [{
        path: '/welcome',
        component: Welcome
      },
      {
        path: '/users',
        component: Users
      }, {
        path: '/rights',
        component: Rights
      }, {
        path: '/roles',
        component: Roles,
        children: [{
          path: '/editrole',
          name: 'EditRole',
          component: EditRole
        }]
      },
      {
        path: '/categories',
        component: Cate,
        children: [{
            path: '/addcate',
            name: 'Addcate',
            component: Addcate
          },
          {
            path: '/editcate',
            name: 'Editcate',
            component: Editcate
          }

        ]
      },
      {
        path: '/params',
        component: Params
      }, {
        path: '/goods',
        component: GoodsList
      }, {
        path: '/goods/add',
        component: Add
      }, {
        path: '/orders',
        component: Order
      }, {
        path: '/reports',
        component: Report
      }
    ]
  }
]

const router = new VueRouter({
  routes,
  mode: 'history'
})

router.beforeEach((to, from, next) => {
  // 访问的是登录页面
  if (to.path === '/login') {
    return next()
  }
  // 访问的不是登录页面，获取token
  const token = window.sessionStorage.getItem('token')
  if (!token) return next('/login')
  next()
})

export default router
